﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Office.Server.SocialData;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using TemplateLibraryConnector.Utility;


namespace TemplateLibraryConnector.Data
{
    public class FavoriteTemplates : BaseTemplates
    {
        private const string LikeTerm = "I like it";

        public FavoriteTemplates(TemplateLibraryConnectorSettings settings) : base(settings)
        {
        }

        public override DataTable Items()
        {
            return GetFavoriteTemplates(Settings.GetTemplateHubAddress(string.Empty)); 
        }

        public DataTable GetFavoriteTemplates(string libraryAddress)
        {
            var items = new List<SPListItem>();

            var serverContext = SPServiceContext.GetContext(SPContext.Current.Site);
            var userProfileManager = new UserProfileManager(serverContext);
            var currentUser = SPContext.Current.Web.CurrentUser.LoginName;
            var dt = new DataTable();

            if (userProfileManager.UserExists(currentUser))
            {
                // Retreive the user profile.
                var userProfile = userProfileManager.GetUserProfile(currentUser);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (var site = new SPSite(libraryAddress))
                    {
                        using (var web = site.OpenWeb())
                        {
                            var favs = GetFavorites(userProfile);
                                            
                            foreach( var item in favs)
                            {
                                try
                                {
                                    var file = web.GetListItem(item.Url.ToString());

                                    if(file.HasPublishedVersion)
                                    {
                                        items.Add(file);
                                    }
                                }
                                catch (Exception)
                                {
                                    // Ops. Cannot load... Template does not exist anymore in hub. Remove it!
                                    UnLike(item.Url);
                                }
                            }
                            dt = TemplateLibraryUtility.ToDataTable(items.ToList());               
                        }
                    }
                });
            }

            return dt;
        }

        public IEnumerable<SocialTag> GetFavorites(UserProfile loginName)
        {
            var hubUrl = Settings.GetTemplateHubAddress(string.Empty);
            var socialTagManager = TagManager;
            //Get Reference to Taxonomy Store (to retrieve 'I Like It' term)
            var term = GetLikeTerm();

            if (term != null)
            {
                
                var socialUrls = from socialUrl in socialTagManager.GetTags(loginName)
                                 where socialUrl.Url.ToString().Contains(hubUrl) 
                                 orderby socialUrl.LastModifiedTime descending
                                 select socialUrl;

                return socialUrls;
            }
            return (IEnumerable<SocialTag>)new List<SocialUrl>();

        }

        public static bool DoILikeThis(Uri uri)
        {
            //Get Reference to Social Data
            var socialTagManager = TagManager;


            //Get Reference to Taxonomy Store (to retrieve 'I Like It' term
            var taxSession = socialTagManager.TaxonomySession;
            var termStore = taxSession.DefaultKeywordsTermStore;
            var termCollection = termStore.KeywordsTermSet.GetTerms(LikeTerm, termStore.DefaultLanguage, false);

            //If terms matched (this should be the case)
            return termCollection.Count == 1 && socialTagManager.GetTags(uri).Any(tag => tag.Term.GetDefaultLabel(termStore.DefaultLanguage) == termCollection[0].GetDefaultLabel(termStore.DefaultLanguage));
        }

        private static SocialTagManager TagManager
        {
            get
            {
                return new SocialTagManager(SPServiceContext.Current);
            }
        }

        public static void Like(Uri uri, string pageTitle)
        {
            var socialTagManager = TagManager;
            var term = GetLikeTerm();

            if (term != null)
            {
                socialTagManager.AddTag(uri, term, pageTitle);
            }

        }

        public static void UnLike(Uri uri)
        {
            SocialTagManager socialTagManager = TagManager;
            var term = GetLikeTerm();

            //If terms matched (this should be the case)
            if (term != null)
            {
                socialTagManager.DeleteTag(uri, term);
            }
        }

        private static Term GetLikeTerm()
        {
            
                Term term = TagManager.TaxonomySession.DefaultKeywordsTermStore.KeywordsTermSet.Terms[LikeTerm];

                if (term != null)
                {
                    return term;
                }

            return null;
    
        }

    }
}
